import { API_URL, filePrefix } from '@/common/constants';
import axios from '@/common/axios';
// var FileSave = require('file-save');

export const downloadFile = (url) => {
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();

  document.body.removeChild(link);
  window.URL.revokeObjectURL(link.href);
};

// export const downloadFile = (folder, file_name) => {
//   let link = document.createElement("a");
//   link.style.display = "none";
//   let host = window.location.host;
//   link.href = filePrefix + folder + "/" + file_name;
//   link.target = "_blank";
//   // a.download = '文件.pdf'
//   document.body.appendChild(link);
//   link.click();

//   document.body.removeChild(link);
//   window.URL.revokeObjectURL(link.href);
// };

export const downloadRes = async (fileName, res) => {
  const url = window.URL.createObjectURL(res);
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  const date = new Date();
  const dateStr = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  link.setAttribute('download', `${fileName}-${dateStr}.xlsx`);
  document.body.appendChild(link);
  link.click();
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
};

export const downloadFile1 = async (folder, file_name) => {
  const index = file_name.lastIndexOf('.');
  const format = file_name.substr(index + 1);
  const url = `${filePrefix + folder}/${file_name}`;
  // 异步申请文件流
  const { data } = await axios.get(url, {
    headers: {
      'Content-Type': 'application/octet-stream',
    },
    responseType: 'blob',
  });
  const file = new Blob([data], {
    type: `application/${format}`,
  });
  // FileSave.saveAs(file, filename);

  return data;
};

export const isImageType = (ext) => {
  const isImage = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].find(
    (item) => item == ext.toLowerCase(),
  );
  return isImage && isImage.length > 0;
};

export const isPdfType = (ext) => {
  return ['pdf'].indexOf(ext.toLowerCase()) !== -1;
};

export const isExcelType = (ext) => {
  return ['xls', 'xlsx'].indexOf(ext.toLowerCase()) !== -1;
};
export const isWordType = (ext) => {
  return ['doc', 'docx'].indexOf(ext.toLowerCase()) !== -1;
};
